# -*- coding: utf-8 -*-
import os
from playsound import playsound  # pip install playsound
import tkinter as tk
import json
import re
from datetime import datetime, timedelta
import requests

login_url = "http://e.arrowzl.cn/jterp/user/login"
token_1 = []
token_url = "http://e.arrowzl.cn/jterp/user/loginByPhone"
list_ID = []  # 空列表保存id
list_DDid = []  # 订单编号
list_SN = []  # 所有sn码，用来统计测试数量
list_Total = []  # 用来结算测试数量
creators = [192]
loginName = ["郑小敏"]


def get_yzm():
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0"}
    params = {"loginName": loginName[0], "password": "e10adc3949ba59abbe56e057f20f883e"}
    response = requests.post(login_url, json=params, headers=headers)
    data = response.json()
    if data.get("code") == 200:
        print("验证码发送成功,正在获取Token")
        token_1.append(data["data"]["token"])  # 提取token
        print('Token获取成功')
    else:
        print(f"验证码发送失败: {data.get('message', '未知错误')}")

    return token_1


def log_in(m, tk):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "Referer": "http://e.arrowzl.cn/user/login",
        "Cookie": "x-hng=lang=zh-CN&domain=e.arrowzl.cn",  # 必须替换
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8",
    }

    params1 = {
        "code": str(m),
        "token": tk
    }
    response = requests.post(token_url, json=params1, headers=headers)
    data = response.json()
    print("正在登录.....")
    if data.get("code") == 200:
        print("登录成功")
    else:
        print(f"登录失败: {data.get('message', '未知错误')}")


def get_zzid(a, bt, et, url, param):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "Referer": url,
        "Cookie": "x-hng=lang=zh-CN&domain=e.arrowzl.cn",  # 必须替换
        "X-Requested-With": "XMLHttpRequest",
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8",
        "x-access-token": a
    }
    params = {
        "search": json.dumps({
            "type": "其它",
            "subType": param,
            "roleType": "全部数据",
            "creator": creators[0],
            "beginTime": bt,  # 修改为要查询的日期
            "endTime": et}),
        "currentPage": 1,
        "pageSize": 200000}

    try:
        response = requests.Session().get(
            "http://e.arrowzl.cn/jterp/depotHead/list",
            headers=headers,
            params=params,
            timeout=10
        )
        if response.status_code == 200:  # 状态码为200说明访问成功
            data = response.text
            # print(data)
            ids = re.findall(r'"id":\s*(\d+)', data)  # 提取id数值
            ddh = re.findall(r'"linkNumber":"([^"]*)"', data)  # 提取订单编号
            for i in range(len(ids)):
                list_ID.append(int(ids[i]))  # 保存ID进list
            for i in range(len(ids)):
                list_DDid.append(str(ddh[i]))  # 保存订单编号进list
                # print(list_DDid[i])
            print(f'页数:', len(list_ID))
    except Exception as e:
        print("完整错误:", str(e))


# 获取组装单中的订单号，sn码，做鸡数量
def run_ok(a, url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "Referer": url,
        "Cookie": "x-hng=lang=zh-CN&domain=e.arrowzl.cn",  # 必须替换
        "X-Requested-With": "XMLHttpRequest",
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json;charset=UTF-8",
        "x-access-token": a
    }
    try:
        for i in range(len(list_ID)):
            params2 = {
                "headerId": list_ID[i],
                "mpList": "",
                "linkType": "basic"
            }
            response = requests.session().get(
                f"http://e.arrowzl.cn/jterp/depotItem/getDetailList?headerId={list_ID[i]}&mpList=&linkType=basic",
                headers=headers,
                params=params2,
                timeout=20
            )
            if response.status_code == 200:
                data = response.json()
                # data中从 data['data']['rows'] 中筛选出categoryName值为'台式机'depotName为'成品仓'snListSure的值不为None中的 snListSure 值,就是最后录到成品仓中的sn
                sn = [
                    row['snListSure']
                    for row in data['data']['rows']
                    if row.get('categoryName') == '台式机'
                       and row.get('depotName') == '成品仓'
                       and row['snListSure'] is not None
                ]
                a = sn[0].count(',')  # 统计，+1就是录得sn的数量
                print(f'{i + 1}=====================\n订单编号:{list_DDid[i]}\nsn码:{sn}\n数量:{a + 1}')
                # 将sn遍历进list_SN用来统计当天组装总数
                for k in range(len(sn)):
                    list_SN.append(sn[k])
        print(f'===========\n总数:{len(list_SN)}台')
        list_SN.clear()

    except Exception as e:
        print("完整错误:", str(e))
        exit()


def slh():
    sound_file = os.path.join(os.path.dirname(__file__), "J.mp3")
    playsound(sound_file)
    root = tk.Tk()
    root.overrideredirect(True)
    width, height = 300, 100
    x = (root.winfo_screenwidth() - width) // 2
    y = (root.winfo_screenheight() - height) // 2
    root.geometry(f"{width}x{height}+{x}+{y}")
    root.configure(bg="#00008B")
    btn = tk.Button(
        root,
        text="GOGOGO",
        command=root.destroy,
        bg="black",  # 黑色背景
        fg="#4CAF50",  # 亮绿色文字 (#4CAF50是墨绿，#00FF00是亮绿)
        font=("Arial", 40, "bold"),  # 加粗
        padx=20,
        pady=10,
        activebackground="#333333",  # 点击时背景变深灰
        activeforeground="#00FF00",  # 点击时保持绿色文字
        relief="raised",  # 3D凸起效果
        borderwidth=3  # 边框加粗
    )
    btn.place(x=0, y=0, relwidth=1, relheight=1)
    root.mainloop()


if __name__ == '__main__':
    urls = ["http://e.arrowzl.cn/bill/upassemble", "http://e.arrowzl.cn/bill/assemble"]
    paramss = ["生产改装", "组装单"]
    slh()
    get_yzm()
    yzm = input('请输入手机短信验证码:\n')
    log_in(yzm, token_1[0])
    while 1:
        while 1:
            Otime = input('输入要查询的起始月日和查看天数用空格隔开如(0606 6):\n').split()
            if len(Otime) > 2:
                print('输入有误,重输')
            else:
                if len(Otime) == 1:
                    Otime.append("0")
                break
        OTime = f"{str(datetime.now().year)}" + Otime[0]
        ragtime = str(datetime.strptime(OTime, "%Y%m%d").date())  # 开始日期
        endtime = str(datetime.strptime(OTime, "%Y%m%d").date() + timedelta(days=int(Otime[1])))  # 结束日期
        get_zzid(token_1[0], ragtime, endtime, urls[0], paramss[0])
        print('改装单数据：')
        run_ok(token_1[0], urls[0])
        list_ID.clear()
        get_zzid(token_1[0], ragtime, endtime, urls[1], paramss[1])
        print('组装单数据：')
        run_ok(token_1[0], urls[0])
        list_ID.clear()
